package com.crissy.datamasking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.crissy.datamasking.common.ErrorCode;
import com.crissy.datamasking.common.Result;
import com.crissy.datamasking.entity.User;
import com.crissy.datamasking.mapper.UserMapper;
import com.crissy.datamasking.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crissy.datamasking.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Crissy-月下闲人
 * @since 2024-04-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public Result toLogin(String username, String password) {
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMETER_ILLEGAL, ErrorCode.PARAMETER_ILLEGAL_MSG);
        }
        User user = userMapper.toLogin(username, password);
        if (BeanUtil.isEmpty(user)) {
            return Result.fail(ErrorCode.USER_PASSWORD_ERROR, ErrorCode.USER_PASSWORD_ERROR_MSG);
        }
        return Result.success(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG, jwtTokenUtil.generateToken(user));
    }

    @Override
    public Result toRegister(String username, String password) {
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMETER_ILLEGAL, ErrorCode.PARAMETER_ILLEGAL_MSG);
        }
        if (userMapper.userExists(username)) {
            return Result.fail(ErrorCode.USER_EXIST, ErrorCode.USER_EXIST_MSG);
        }
        int insert = userMapper.insert(new User(username, password));
        if (insert <= 0) {
            return Result.fail(ErrorCode.ERROR, ErrorCode.ERROR_MSG);
        }
        return Result.success(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG);
    }

    @Override
    public Result isLogin(String token) {
        if (jwtTokenUtil.isTokenExpired(token)) {
            return Result.fail(ErrorCode.TOKEN_EXPIRED, ErrorCode.TOKEN_EXPIRED_MSG);
        }
        return Result.success(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG);
    }
}
